package com.yc.jpyy.mobile.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;
import com.yc.jpyy.base.controller.BaseController;

@Controller
@RequestMapping(value = "/txt")
public class WriteTxtController extends BaseController{
	
	@SuppressWarnings("finally")
	@RequestMapping(value = "/writeTxt", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String writeTxt(HttpServletRequest request)
			throws UnsupportedEncodingException {
		RestResponse response = new RestResponse();
		try {
			// Json字符串
			String JsonString= URLDecoder.decode(request.getParameter("JsonString"));
			//String JsonString= URLDecoder.decode("0,1530178311,0,2018-06-28 17:37:28,0,0,0|0|0|0|0,2018-06-28 17:51:25,,0,0,,00000187067633311806280001;");
			if(JsonString!=null && !JsonString.isEmpty()){
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS");
				String str = now.format(f);
				String fileName = "studyRecord_" + str + "_1.raw"; 
				String path = Config.getStudyRecordSave() + "\\" + fileName;
				File currfile = new File(path);
				if (!currfile.exists()) {
					currfile.createNewFile();// 如果不存在该文件，则创建
				}
				FileWriter fw = new FileWriter(path, true);
				String[] json = JsonString.split(";");
				for(int i = 0;i < json.length;i ++){
					if(i == 0){
						fw.write(json[i]);
					}else{
						fw.write(System.getProperty("line.separator"));
					    fw.write(json[i]);
					}	
				}
				fw.close();
			}else{
				response.setErrorcode(1);
				response.setMessage("Json字符串为空...");
			}
		} catch (Exception e) {
			response.setReturnMsg(1,"Json字符写入失败！");
		} finally {
			return response.toJSON();
		}
	}

}
